﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Threading;
using System.Collections;


namespace mns
{
    
    class Monitor
    {


        public static int ReceiveId = -1;
        public static int SendId = -1;

        enum State { CHECKTASK, WAITFORPROCESSING };
        private Monitor()
        {
            ;
        }
        static State state;

        static List<int> notifylist;

        static void Initial()
        {
            state = State.CHECKTASK;
            notifylist = new List<int>();
            notifylist.Clear();

            //
            TaskManage.Initial();

        }
               
        //wait a notification through checking all of the tasks
        static void CheckTask()
        {           
            //Check all of the tasks
            if(notifylist.Count == 0)
            {
                TaskManage.PeriodRun(ref notifylist);
                //if more than one tasks need to be given, send msg to the ui thread
                if (notifylist.Count != 0)
                {
                    UIMM work_uimm = new UIMM();
                    work_uimm.cmd = UIMM.UIMM_MSG.NOTIFY;
                    work_uimm.data = notifylist;
                    MSGL.SendMessage(SendId, work_uimm);
                    state = State.WAITFORPROCESSING;
                }
            }            
        }


        //
        static void WaitForProcess()
        {
            //
            object o;
            if(MSGL.GetMessage(ReceiveId,out o))
            {
                UIMM work_uimm = (UIMM)o;
                switch(work_uimm.cmd)
                {
                    case UIMM.UIMM_MSG.RESPONSE:
                        state = State.CHECKTASK;
                        // handle the message
                        notifylist.Clear();
                        break;
                }
            }

        }

        //Check 
        static void Check()
        {
            switch(state)
            {
                case State.CHECKTASK:
                    CheckTask();
                    break;
                case State.WAITFORPROCESSING:
                    WaitForProcess();
                    break;
            }
        }

        //Run
        static public void Run()
        {
            //intial
            Initial();

            //initial some parameters
            while (true)
            {
                Check();
                Thread.Sleep(10000);        
            }

        }

    }

}
